// pages/login/login.js
const app = getApp();
const db = wx.cloud.database();
Page({
  data: {
    height: "0rpx"
  },
  onLoad: function (options) {
    this.setData({
      height: wx.getSystemInfoSync().windowHeight + 'px'
    })
  },



  // 获取授权
  getUserInfo: function (e) {
    wx.showLoading({
      title: '正在登录',
    })
    console.log(e.detail.userInfo);
    wx.cloud.callFunction({
      name: 'login',
      complete: res => {
        db.collection("user").where({
          _openid: res.result.openid
        }).count().then(res => {

          wx.navigateBack({
            delta: 1
          })
          if (res.total == 0) {
            db.collection('user').add({
              data: {
                _openid: e.detail.userInfo._openid,
                nickName: e.detail.userInfo.nickName,
                avatarUrl: e.detail.userInfo.avatarUrl,
              },
              success: res => {
                wx.showToast({
                  title: '登录成功',
                })
                wx.navigateBack({
                  delta: 1
                })
              },
              fail: err => {
                wx.showToast({
                  icon: 'none',
                  title: '登录失败'
                })
              }
            })
            wx.navigateBack({
              delta: 1
            })
          } else {
            wx.navigateBack({
              delta: 1
            })
          }
        })
      }
    })
  },
  notLogin: function () {
    wx.navigateBack({
      delta: 1
    })
  }
})